const randomstr = require('randomstring')
const xmljs = require('xml-js')

const genRandomStr = (len) => {
  return randomstr.generate(len)
}

const xml2js = (xml) => {

  let obj = xmljs.xml2js(xml, {
    compact: true,
    cdataKey: 'value',
    textKey: 'value'
  }).xml;

  //数据的扁平化
  let newObj = Object.keys(obj).reduce((item, key) => {
    item[key] = obj[key]['value'];
    return item;
  }, {})

  return newObj;
}

const js2xml = (params) => {
  return xmljs.json2xml(params, {
    compact: true
  })
}

module.exports = {
  genRandomStr,
  js2xml,
  xml2js
}